﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Net.Chirash.Twitter.TwitterClient;
using Net.Chirash.Twitter.TwitterDatabase;

namespace Net.Chirash.Twitter.TweetZone.WindowComponents.ViewModels
{
    public class RecentStatusContainerViewModel
        : TimelineContainerViewModel
    {
        #region public methods

        public RecentStatusContainerViewModel()
            : base(TimelineTypes.Other)
        { }

        public override string ContainerTitle
        {
            get
            {
                return this.TaskName;
            }
        }

        public override void TaskSubscribe()
        {
            ReceiveUserStreams();
        }

        #endregion

        #region protected methods

        protected override string TaskName
        {
            get
            {
                return "Recent";
            }
        }

        protected override void RefreshDataProviding(RefreshArgs<Status> e)
        {
            lock (lockCache)
            {
                e.ResultEnumerable = this.cache.Take(e.RequiredCount);
            }
        }

        protected override void PagingDataProviding(PagingEventArgs<Status> e)
        {
            lock (lockCache)
            {
                e.ResultEnumerable = this.cache.Where((sta) => sta.StatusID < e.LastData.StatusID - 1)
                                               .Take(e.RequiredCount);
            }
        }

        public override void OnNext(IEnumerable<TwitterData> value)
        {
            const int preserveCount = 500;

            if (value.Count() > 0 && value is IEnumerable<Status>)
            {
                lock (lockCache)
                {
                    var addingList = value as IEnumerable<Status>;
                    cache.AddRange(addingList.Where((sta) => sta != null));

                    //order by statusid desc

                    if (cache.Count > preserveCount)
                    {
                        cache.RemoveRange(preserveCount - 1, cache.Count - preserveCount);
                    }

                    cache.Sort(new Comparison<Status>((A, B) => -1 * A.StatusID.CompareTo(B.StatusID)));

                }
            }

            base.OnNext(value);
        }

        #endregion

        #region private members

        private List<Status> cache = new List<Status>();
        private volatile object lockCache = new object();

        #endregion
    }
}
